#!coding:utf-8
# vim: tabstop=4 shiftwidth=4 softtabstop=4
import tempfile
from pyExcelerator import *

from django.db import transaction
from django.http import HttpResponse
from rest_framework import status
from rest_framework.response import Response

from cvirt.manager.models import User, Instance
from cvirt.manager.serializers import UserSerializer
from cvirt.manager.views import NamedAPIViewMixIn, BaseRetriveAPIView,BaseListAPIView
from cvirt.common import translate as _


class Users(NamedAPIViewMixIn, BaseListAPIView):
    model = User
    serializer_class = UserSerializer

    def create(self, request, *args, **kwargs):
        userparams = self.get_params('user')
        if userparams:
            if User.objects.first(username=userparams['username']):
                return Response(_('用户名%s已经存在' % userparams['username']),status.HTTP_400_BAD_REQUEST)
            user = User.objects.create(username=userparams['username'],organize=userparams['organize'],
                                       password=userparams['password'],phone=userparams['phone'],

            )

            return Response(self.get_serializer(user).data)
        return Response('username and password can not be null',status.HTTP_400_BAD_REQUEST)

    def _update_status(self,status):
        ids = self.get_params('ids')
        for id in ids:
            user = User.objects.get_or_none(pk=id)
            if user:
                user.update(dict(status=status))
        return Response(status=200)

    def active(self,req,*args,**kwargs):
        return self._update_status('offline')

    def deny(self,req,*args,**kwargs):
        return self._update_status('deny')

    def _get(self, request, *args, **kwargs):

        dataset = User.objects.all()
        result = self.paginate(request, dataset, self.get_serializer_class())
        return Response(result)


    def delete(self, request, *args, **kwargs):
        ids = self.get_params('ids')
        for id in ids:
            user = User.objects.get_or_none(pk=id)
            if user:
                user.remove()
        return Response(status=status.HTTP_200_OK)

    def export_users(self,req,*args,**kwargs):
        users = User.objects.all()
        w = Workbook()
        ws = w.add_sheet(u'用户')
        def filter_none(value):
            return '' if not value else value

        ws.write(0,0,u'用户名')
        ws.write(0,1,u'密码')
        ws.write(0,2,u'组织(可选)')
        ws.write(0,3,u'电话(可选)')

        for r,user in enumerate(users):
            r = r+1
            ws.write(r,0,user.username)
            ws.write(r,1,user.password)
            ws.write(r,2,filter_none(user.organize))
            ws.write(r,3,filter_none(user.phone))

        _,xls = tempfile.mkstemp()
        w.save(xls)

        response = HttpResponse(file(xls).read(), content_type='application/xls')
        response['Content-Disposition'] = 'attachment; filename=users.xls'
        return response

    def import_users(self,req,*args,**kwargs):
        try:
            __,xls = tempfile.mkstemp()
            with file(xls,'wb') as f:
                f.write(req.FILES['file'].read())

            sheets = parse_xls(xls)[0][1]

            def handle(key):
                return sheets[key] if sheets.has_key(key) else None

            #读出的数据是key-value格式:(row,cell):'<name>',第一行是title,忽略掉
            #cell固定为7个属性，找到row最大行数,从1开始
            result = []
            with transaction.commit_on_success():
                for i in range(1,max(sheets.keys())[0]+1):
                    if not User.objects.get_or_none(username=handle((i,0))):
                        if len(handle((i,1))) >=6 and str(int(handle((i,3)))).isdigit():#密码大于6位，手机号码为数字
                            user = User.objects.create(username=handle((i,0)),organize=handle((i,2)),password=handle((i,1)),
                                                       phone=handle((i,3)))
                            result.append(user)

            return Response(self.get_serializer(result,many=True).data,status=200)

        except Exception as e:
            import traceback
            traceback.print_exc()

        return Response(_("这不是合法的excel文件，请选择合法的excel文件"), status=status.HTTP_400_BAD_REQUEST)


class UserInfo(NamedAPIViewMixIn,BaseRetriveAPIView):
    model = User
    serializer_class = UserSerializer

    @transaction.commit_on_success
    def attach(self,req,*args,**kwargs):
        user = User.objects.get_or_none(pk=self.pk)
        vmids = self.get_params('ids')

        if user:
            user.update(dict(instance_set=[]))
            for vmid in vmids:
                vm = Instance.objects.get_or_none(pk=vmid)
                if vm:
                    vm.update(dict(user=user))
            return Response(status=200)

        return Response("user can not be null",status.HTTP_400_BAD_REQUEST)

    def update(self,req,*args,**kwargs):
        userparams = self.get_params('user')
        if userparams:
            user = User.objects.get_or_none(pk=self.pk)
            if user:
                user.update(dict(organize=userparams['organize'],
                                           password=userparams['password'],phone=userparams['phone']))

            return Response(status=status.HTTP_200_OK)
        return Response('username and password can not be null',status.HTTP_400_BAD_REQUEST)